package cn.wuxing.mediation.system.service.impl;

import cn.wuxing.mediation.common.core.domain.AjaxResult;
import cn.wuxing.mediation.common.core.domain.entity.SysUser;
import cn.wuxing.mediation.common.utils.EncryptionUtils;
import cn.wuxing.mediation.common.utils.SecurityUtils;
import cn.wuxing.mediation.common.utils.des.DESUtil;
import cn.wuxing.mediation.system.domain.vo.*;
import cn.wuxing.mediation.system.mapper.AnalysisMapper;
import cn.wuxing.mediation.system.mapper.SysUserMapper;
import cn.wuxing.mediation.system.service.ISAnalysisService;
import cn.wuxing.mediation.system.util.Desensitization;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class AnalysisServiceImpl implements ISAnalysisService {

    @Resource
    private AnalysisMapper analysisMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //时间筛选
    private QueryTimeVo getTime(String query) {
        QueryTimeVo queryTimeVo = new QueryTimeVo();
        Calendar d = Calendar.getInstance();
        Date now = new Date();
        if (query == null) {
            return queryTimeVo;
        }
        switch (query) {
            case "1"://按周
                d.setTime(now);
                d.add(Calendar.DATE, -7);
                queryTimeVo.setStartTime(simpleDateFormat.format(d.getTime()));
                queryTimeVo.setEndTime(simpleDateFormat.format(now));
                break;
            case "15":
                d.setTime(now);
                d.add(Calendar.DATE, -15);
                queryTimeVo.setStartTime(simpleDateFormat.format(d.getTime()));
                queryTimeVo.setEndTime(simpleDateFormat.format(now));
                break;
            case "2":
                d.setTime(now);
                d.add(Calendar.MONTH, -1);
                queryTimeVo.setStartTime(simpleDateFormat.format(d.getTime()));
                queryTimeVo.setEndTime(simpleDateFormat.format(now));
                break;
            case "3":
                d.setTime(now);
                d.add(Calendar.YEAR, -1);
                queryTimeVo.setStartTime(simpleDateFormat.format(d.getTime()));
                queryTimeVo.setEndTime(simpleDateFormat.format(now));
                break;
        }
        return queryTimeVo;
    }

    //范围
    private QueryTimeVo getTimeRange(String query) {
        QueryTimeVo queryTimeVo = new QueryTimeVo();
        Calendar d = Calendar.getInstance();
        Date now = new Date();
        if (query == null) {
            return queryTimeVo;
        }
        switch (query) {
            case "1"://近3周
                d.setTime(now);
                d.add(Calendar.DATE, -21);
                queryTimeVo.setStartTime(simpleDateFormat.format(d.getTime()));
                queryTimeVo.setEndTime(simpleDateFormat.format(now));
                break;
            case "2"://近3月
                d.setTime(now);
                d.add(Calendar.MONTH, -3);
                queryTimeVo.setStartTime(simpleDateFormat.format(d.getTime()));
                queryTimeVo.setEndTime(simpleDateFormat.format(now));
                break;
            case "3"://近3年
                d.setTime(now);
                d.add(Calendar.YEAR, -3);
                queryTimeVo.setStartTime(simpleDateFormat.format(d.getTime()));
                queryTimeVo.setEndTime(simpleDateFormat.format(now));
                break;
        }
        return queryTimeVo;
    }

    //地区权限以及加密姓名、身份证和联系人
    private AnalysisQueryVo getAreaRole(AnalysisQueryVo analysisQueryVo) {
        if(analysisQueryVo.getIdCard()!=null){
            if(Desensitization.checkStrIncludeSpecial(analysisQueryVo.getIdCard())){
                analysisQueryVo.setEncryptIdCard(DESUtil.encrypt(analysisQueryVo.getIdCard()));
            }
        }
        if(analysisQueryVo.getName()!=null){
            if(Desensitization.checkStrIncludeChinese(analysisQueryVo.getName())){
                analysisQueryVo.setEncryptName(DESUtil.encrypt(analysisQueryVo.getName()));
            }
        }
        if(analysisQueryVo.getOrganizeName()!=null){
            if(Desensitization.checkStrIncludeChinese(analysisQueryVo.getOrganizeName())){
                analysisQueryVo.setEncryptOrganizeName(DESUtil.encrypt(analysisQueryVo.getOrganizeName()));
            }
        }
        Long userId = SecurityUtils.getUserId();
        if (userId == 1) {
            analysisQueryVo.setUserAreaId(null);
            return analysisQueryVo;
        }
        Long areaRole = sysUserMapper.selectUserAreaByUserId(userId);
        if (areaRole == 50) {//区级权限
            analysisQueryVo.setUserAreaId(null);
        } else {
            analysisQueryVo.setUserAreaId(areaRole);
        }
        return analysisQueryVo;
    }

    //根据idCard查询事件总数列表
    private AnalysisQueryVo getIdCardByUserId(AnalysisQueryVo analysisQueryVo) {
        Long userId = analysisQueryVo.getApplicantId();//获取要查询事件列表的userId
        if (userId != null) {
            String idCard = analysisMapper.selectIdCardByApplicantId(userId);//查询idCard
            if(idCard!=null){
                analysisQueryVo.setIdCard(idCard);
                if(Desensitization.checkStrIncludeSpecial(idCard)){//是否加密
                    analysisQueryVo.setEncryptIdCard(DESUtil.decrypt(idCard));
                }
            }
        }
        return analysisQueryVo;
    }

    @Override
    public List<AnalysisVo> getDisputeCount(AnalysisQueryVo analysisQueryVo) {
        Long areaId = analysisQueryVo.getId();
        if (areaId != null) {
            if (areaId == 50) {
                areaId = null;
                analysisQueryVo.setId(areaId);//查全部
            }
        }
        return analysisMapper.getDispute(getAreaRole(analysisQueryVo));
    }

    @Override
    public List<AnalysisTypeVo> getDisputeCountByType(AnalysisQueryVo analysisQueryVo) {
        return analysisMapper.getDisputeType(getAreaRole(analysisQueryVo));
    }

    @Override
    public List<DisputeAnalysisVo> disputesAnalysis(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
        return analysisMapper.disputesAnalysis(getAreaRole(analysisQueryVo));
    }

    @Override
    public AjaxResult disputeSubject(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
//        List<DisputeSubjectVo> disputeSubjectVos = analysisMapper.disputeSubject(analysisQueryVo);
        AnalysisQueryVo areaRole = getAreaRole(analysisQueryVo);//获取用户的所属地区权限
        String applicantType = areaRole.getApplicantType();
        if (applicantType == null) {
            return AjaxResult.error("查询失败");
        }
        if (applicantType.equals("1")) {//自然人
            List<DisputeSubjectVo> list = analysisMapper.disputeSubjectWithApplicant(areaRole);
            list.forEach(i -> {
                String name = i.getName();
                String idCard = i.getIdCard();
                String phone = i.getPhone();
                if (!Desensitization.checkStrIncludeChinese(name)) {//判断名字是否是中文，未加密
                    name = DESUtil.decrypt(name);
                    if (idCard != null) {
                        idCard = DESUtil.decrypt(idCard);
                    }
                    if (phone != null) {
                        phone = DESUtil.decrypt(phone);
                    }
                }
                i.setName(Desensitization.desensitizedName(name));
                i.setIdCard(Desensitization.idCardDesensitization(idCard));
                i.setPhone(Desensitization.mobilePhoneDesensitization(phone));
            });
            Long total = analysisMapper.disputeSubjectCount(areaRole);
            return AjaxResult.successPage(list, total);
        }
        //法人组织、非法人组织
        List<DisputeSubjectVo> list=analysisMapper.disputeSubjectWithOrganize(areaRole);
        list.forEach(i -> {
            String name = i.getName();
            String idCard = i.getIdCard();
            String phone = i.getPhone();
            String organizeName = i.getOrganizeName();
            if (!Desensitization.checkStrIncludeChinese(name)) {//判断名字是否是中文，未加密
                name = DESUtil.decrypt(name);
                if (idCard != null) {
                    idCard = DESUtil.decrypt(idCard);
                }
                if (phone != null) {
                    phone = DESUtil.decrypt(phone);
                }
                if (organizeName != null) {
                    organizeName = DESUtil.decrypt(organizeName);
                }
            }
            i.setName(Desensitization.desensitizedName(name));
            i.setIdCard(Desensitization.idCardDesensitization(idCard));
            i.setPhone(Desensitization.mobilePhoneDesensitization(phone));
            i.setOrganizeName(Desensitization.custNameDesensitization(organizeName));
        });
        Long total=analysisMapper.disputeSubjectWithOrganizeCount(areaRole);
        return AjaxResult.successPage(list,total);
    }

    @Override
    public List<DisputeTrendVo> disputeTrend(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }

        String dataType = analysisQueryVo.getDataType();
        if (dataType != null) {//默认
            QueryTimeVo timeVo = getTime(dataType);
            analysisQueryVo.setStartTime(timeVo.getStartTime());
            analysisQueryVo.setEndTime(timeVo.getEndTime());
        } else {
            String startTime = analysisQueryVo.getStartTime();
            String endTime = analysisQueryVo.getEndTime();
            if (startTime != null && endTime != null) {
                analysisQueryVo.setStartTime(startTime + " 00:00:00");
                analysisQueryVo.setEndTime(endTime + " 23:59:59");
            }
            if (endTime == null) {
                analysisQueryVo.setStartTime(startTime + " 00:00:00");
                analysisQueryVo.setEndTime(startTime + " 23:59:59");
            }
            if (startTime == null && endTime == null) {
                QueryTimeVo timeVo = getTime("1");
                analysisQueryVo.setStartTime(timeVo.getStartTime());
                analysisQueryVo.setEndTime(timeVo.getEndTime());
            }
        }
        return analysisMapper.disputeTrend(getAreaRole(analysisQueryVo));
    }

    @Override
    public AjaxResult disputeAge(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
//        analysisMapper.disputeAge(analysisQueryVo);
        AnalysisQueryVo areaRole = getAreaRole(analysisQueryVo);
        String applicantType = areaRole.getApplicantType();
        if (applicantType == null) {
            return AjaxResult.error("查询失败");
        }
        if(applicantType.equals("1")){
            List<DisputeAgeVo> list = analysisMapper.disputeAgeWithApplicant(areaRole);
            list.forEach(i -> {
                String name = i.getName();
                String idCard = i.getIdCard();
                String phone = i.getPhone();
                if (!Desensitization.checkStrIncludeChinese(name)) {//判断名字是否是中文，未加密
                    name = DESUtil.decrypt(name);
                    if (idCard != null) {
                        idCard = DESUtil.decrypt(idCard);
                    }
                    if (phone != null) {
                        phone = DESUtil.decrypt(phone);
                    }
                }
                i.setName(Desensitization.desensitizedName(name));
                i.setIdCard(Desensitization.idCardDesensitization(idCard));
                i.setPhone(Desensitization.mobilePhoneDesensitization(phone));
            });
            Long total = analysisMapper.disputeAgeCount(areaRole);
            return AjaxResult.successPage(list, total);
        }
        List<DisputeAgeVo> list = analysisMapper.disputeAgeWithOrganize(areaRole);
        list.forEach(i -> {
            String name = i.getName();
            String idCard = i.getIdCard();
            String phone = i.getPhone();
            String organizeName = i.getOrganizeName();
            if (!Desensitization.checkStrIncludeChinese(name)) {//判断名字是否是中文，未加密
                name = DESUtil.decrypt(name);
                if (idCard != null) {
                    idCard = DESUtil.decrypt(idCard);
                }
                if (phone != null) {
                    phone = DESUtil.decrypt(phone);
                }
                if (organizeName != null) {
                    organizeName = DESUtil.decrypt(organizeName);
                }
            }
            i.setName(Desensitization.desensitizedName(name));
            i.setIdCard(Desensitization.idCardDesensitization(idCard));
            i.setPhone(Desensitization.mobilePhoneDesensitization(phone));
            i.setOrganizeName(Desensitization.custNameDesensitization(organizeName));
        });
        Long total = analysisMapper.disputeAgeOrganizeCount(areaRole);
        return AjaxResult.successPage(list, total);
    }

    @Override
    public AjaxResult disputeSex(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
//        analysisMapper.disputeSex(analysisQueryVo);
        AnalysisQueryVo areaRole = getAreaRole(analysisQueryVo);
        String applicantType = areaRole.getApplicantType();
        if (applicantType == null) {
            return AjaxResult.error("查询失败");
        }
        if(applicantType.equals("1")){
            List<DisputeSexVo> list = analysisMapper.disputeSexWithApplicant(areaRole);
            list.forEach(i -> {
                String name = i.getName();
                String idCard = i.getIdCard();
                String phone = i.getPhone();
                if (!Desensitization.checkStrIncludeChinese(name)) {//判断名字是否是中文，未加密
                    name = DESUtil.decrypt(name);
                    if (idCard != null) {
                        idCard = DESUtil.decrypt(idCard);
                    }
                    if (phone != null) {
                        phone = DESUtil.decrypt(phone);
                    }
                }
                i.setName(Desensitization.desensitizedName(name));
                i.setIdCard(Desensitization.idCardDesensitization(idCard));
                i.setPhone(Desensitization.mobilePhoneDesensitization(phone));
            });
            Long total = analysisMapper.disputeSexCount(areaRole);
            return AjaxResult.successPage(list, total);
        }
        List<DisputeSexVo> list = analysisMapper.disputeSexWithOrganize(areaRole);
        list.forEach(i -> {
            String name = i.getName();
            String idCard = i.getIdCard();
            String phone = i.getPhone();
            String organizeName = i.getOrganizeName();
            if (!Desensitization.checkStrIncludeChinese(name)) {//判断名字是否是中文，未加密
                name = DESUtil.decrypt(name);
                if (idCard != null) {
                    idCard = DESUtil.decrypt(idCard);
                }
                if (phone != null) {
                    phone = DESUtil.decrypt(phone);
                }
                if (organizeName != null) {
                    organizeName = DESUtil.decrypt(organizeName);
                }
            }
            i.setName(Desensitization.desensitizedName(name));
            i.setIdCard(Desensitization.idCardDesensitization(idCard));
            i.setPhone(Desensitization.mobilePhoneDesensitization(phone));
            i.setOrganizeName(Desensitization.custNameDesensitization(organizeName));
        });
        Long total = analysisMapper.disputeSexOrganizeCount(areaRole);
        return AjaxResult.successPage(list, total);
    }

    @Override
    public List<DisputeTimeVo> disputeTime(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
        String dataType = analysisQueryVo.getDataType();
        if (dataType != null) {
            QueryTimeVo timeRange = getTimeRange(dataType);
            analysisQueryVo.setStartTime(timeRange.getStartTime());
            analysisQueryVo.setEndTime(timeRange.getEndTime());
        } else {
            String startStr = analysisQueryVo.getStartTime();
            if (startStr == null) {//时间范围没有 近3周
//                QueryTimeVo timeRange = getTimeRange("1");
//                analysisQueryVo.setStartTime(timeRange.getStartTime());
//                analysisQueryVo.setEndTime(timeRange.getEndTime());
                analysisQueryVo.setStartTime("");
                analysisQueryVo.setEndTime("");
            } else {
                if (startStr.contains("到")) {
                    String[] strArr = startStr.split("到");
                    String str1 = strArr[0];
                    String str2 = strArr[1];
                    analysisQueryVo.setStartTime(str1);
                    analysisQueryVo.setEndTime(str2);
                }
            }
        }
        return analysisMapper.disputeTime(getAreaRole(analysisQueryVo));
    }

    @Override
    public List<DisputeTimeAreaVo> disputeTimeArea(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
        String dataType = analysisQueryVo.getDataType();
        if (dataType != null) {
            QueryTimeVo timeRange = getTimeRange(dataType);
            analysisQueryVo.setStartTime(timeRange.getStartTime());
            analysisQueryVo.setEndTime(timeRange.getEndTime());
        } else {
            String startStr = analysisQueryVo.getStartTime();
            if (startStr == null) {//时间范围没有 近3周
//                QueryTimeVo timeRange = getTimeRange("1");
//                analysisQueryVo.setStartTime(timeRange.getStartTime());
//                analysisQueryVo.setEndTime(timeRange.getEndTime());
                analysisQueryVo.setStartTime("");
                analysisQueryVo.setEndTime("");
            } else {
                if (startStr.contains("到")) {
                    String[] strArr = startStr.split("到");
                    String str1 = strArr[0];
                    String str2 = strArr[1];
                    analysisQueryVo.setStartTime(str1);
                    analysisQueryVo.setEndTime(str2);
                }
            }
        }
        return analysisMapper.disputeTimeArea(getAreaRole(analysisQueryVo));
    }

    @Override
    public AjaxResult disputeTimeSubject(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
        String dataType = analysisQueryVo.getDataType();
        if (dataType != null) {
            QueryTimeVo timeRange = getTimeRange(dataType);
            analysisQueryVo.setStartTime(timeRange.getStartTime());
            analysisQueryVo.setEndTime(timeRange.getEndTime());
        } else {
            String startStr = analysisQueryVo.getStartTime();
            if (startStr == null) {//时间范围没有 近3周
//                QueryTimeVo timeRange = getTimeRange("1");
//                analysisQueryVo.setStartTime(timeRange.getStartTime());
//                analysisQueryVo.setEndTime(timeRange.getEndTime());

                analysisQueryVo.setStartTime("");
                analysisQueryVo.setEndTime("");
            } else {
                if (startStr.contains("到")) {
                    String[] strArr = startStr.split("到");
                    String str1 = strArr[0];
                    String str2 = strArr[1];
                    analysisQueryVo.setStartTime(str1);
                    analysisQueryVo.setEndTime(str2);
                }
            }
        }
//        analysisMapper.disputeTimeSubject(analysisQueryVo);
        AnalysisQueryVo areaRole = getAreaRole(analysisQueryVo);
        String applicantType = areaRole.getApplicantType();
        if (applicantType == null) {
            return AjaxResult.error("查询失败");
        }
        if(applicantType.equals("1")){
            List<DisputeTimeSubjectVo> list = analysisMapper.disputeTimeSubjectWithApplicant(areaRole);
            list.forEach(i -> {
                String name = i.getName();
                String idCard = i.getIdCard();
                String phone = i.getPhone();
                if (!Desensitization.checkStrIncludeChinese(name)) {
                    name = DESUtil.decrypt(name);
                    idCard = DESUtil.decrypt(idCard);
                    phone = DESUtil.decrypt(phone);
                }
                i.setName(Desensitization.desensitizedName(name));
                i.setIdCard(Desensitization.idCardDesensitization(idCard));
                i.setPhone(Desensitization.mobilePhoneDesensitization(phone));
            });
            Long total = analysisMapper.disputeTimeSubjectCount(areaRole);
            return AjaxResult.successPage(list, total);
        }
        List<DisputeTimeSubjectVo> list = analysisMapper.disputeTimeSubjectWithOrganize(areaRole);
        list.forEach(i -> {
            String name = i.getName();
            String idCard = i.getIdCard();
            String phone = i.getPhone();
            String organizeName = i.getOrganizeName();
            if (!Desensitization.checkStrIncludeChinese(name)) {//判断名字是否是中文，未加密
                name = DESUtil.decrypt(name);
                if (idCard != null) {
                    idCard = DESUtil.decrypt(idCard);
                }
                if (phone != null) {
                    phone = DESUtil.decrypt(phone);
                }
                if (organizeName != null) {
                    organizeName = DESUtil.decrypt(organizeName);
                }
            }
            i.setName(Desensitization.desensitizedName(name));
            i.setIdCard(Desensitization.idCardDesensitization(idCard));
            i.setPhone(Desensitization.mobilePhoneDesensitization(phone));
            i.setOrganizeName(Desensitization.custNameDesensitization(organizeName));
        });
        Long total = analysisMapper.disputeTimeSubjectOrganizeCount(areaRole);
        return AjaxResult.successPage(list, total);
    }

    @Override
    public List<DisputeMediatorVo> disputeMediatorsAll(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
        return analysisMapper.disputeMediatorsAll(getAreaRole(analysisQueryVo));
    }

    @Override
    public List<DisputeMediatorTimeVo> disputeMediatorsTime(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
        return analysisMapper.disputeMediatorsTime(getAreaRole(analysisQueryVo));
    }

    @Override
    public List<DisputeMediatorTypeVo> disputeMediatorsType(AnalysisQueryVo analysisQueryVo) {
        Long id = analysisQueryVo.getId();
        if (id != null) {
            if (id == 50) {
                analysisQueryVo.setId(null);
            }
        }
        return analysisMapper.disputeMediatorsType(getAreaRole(analysisQueryVo));
    }

    @Override
    public AjaxResult disputeList(AnalysisQueryVo analysisQueryVo) {
        analysisQueryVo = getIdCardByUserId(analysisQueryVo);
        List<DisputeVo> disputeVos = analysisMapper.disputeList(analysisQueryVo);
        Long total = analysisMapper.disputeListCount(analysisQueryVo);
        return AjaxResult.successPage(disputeVos, total);
    }
}
